import 'dart:collection';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:opene/JhPickerTool.dart';
import 'package:opene/app_constant.dart';
import 'package:opene/app_theme.dart';
import 'package:opene/app_utils.dart';
import 'package:opene/base/base_state.dart';
import 'package:opene/base/loading.dart';
import 'package:opene/base/scan_code.dart';
import 'package:opene/net/method/base_method.dart';
import 'package:opene/net/network_manager.dart';
import 'package:opene/net/response/base_response.dart';
import 'package:opene/ui/putaway/putawaydialogscreen.dart';
import 'package:opene/ui/putaway/putawaymodel.dart';
import 'package:opene/ui/returns/finalprocess/finalprocessrpsreen.dart';
import 'package:opene/ui/returns/returnsdialogscreen.dart';
import 'package:opene/ui/returns/returnsmodel.dart';
import 'package:toast/toast.dart';

class FinalProcessTrkScreen extends StatelessWidget {
  String oldIbLpn;
  String batchNo;
  List<FinalProcessLpn> finalProcessLpns;

  FinalProcessTrkScreen({this.oldIbLpn, this.batchNo, this.finalProcessLpns});

  @override
  Widget build(BuildContext context) {
    return FinalProcessTrkScreenPage(oldIbLpn: oldIbLpn, batchNo: batchNo, finalProcessLpns: finalProcessLpns);
  }
}

class FinalProcessTrkScreenPage extends StatefulWidget {
  String oldIbLpn;
  String batchNo;
  List<FinalProcessLpn> finalProcessLpns;

  FinalProcessTrkScreenPage({this.oldIbLpn, this.batchNo, this.finalProcessLpns});

  @override
  _FinalProcessTrkPageState createState() => _FinalProcessTrkPageState(oldIbLpn: oldIbLpn, batchNo: batchNo, data: finalProcessLpns);
}

class _FinalProcessTrkPageState extends BaseState<FinalProcessTrkScreen> {
  String oldIbLpn;
  String batchNo;
  List<FinalProcessLpn> data;

  FinalProcessTrk finalProcessTrk;
  bool retape = false;

  final TextEditingController skuEditingController = TextEditingController();
  final TextEditingController qtyEditingController = TextEditingController();
  FocusNode textFiledNode = FocusNode();
  FocusNode skuFocusNode = FocusNode();
  FocusNode qtyFocusNode = FocusNode();

  _FinalProcessTrkPageState({this.oldIbLpn, this.batchNo, this.data});

  @override
  String setTitle({String title}) {
    return !Utils.isEmpty(title) ? title : "FinalProcess:TRK#";
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  void dispose() {
    textFiledNode.dispose(); // 不要忘记销毁FocusNode
    skuFocusNode.dispose(); // 不要忘记销毁FocusNode
    qtyFocusNode.dispose(); // 不要忘记销毁FocusNode
    super.dispose();
  }

  @override
  Widget getViewBinding() {
    return Padding(
      padding: const EdgeInsets.only(left: 15, top: 10, right: 15),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Text(
                "BatchNo: ",
                style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
              ),
              Text(
                Utils.getStringisEmpty(batchNo),
                style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
              ),
            ],
          ),
          Row(
            children: [
              Text(
                "Original LPN: ",
                style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
              ),
              Text(
                Utils.getStringisEmpty(oldIbLpn),
                style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
              ),
            ],
          ),
          SizedBox(
            height: 5,
          ),
          Row(
            children: [
              Expanded(
                flex: 1,
                child: ConstrainedBox(
                  constraints: BoxConstraints(maxHeight: 35),
                  child: TextField(
                    focusNode: textFiledNode,
                    controller: textEditingController,
                    textInputAction: TextInputAction.search,
                    onSubmitted: (String text) {
                      print('Searching for $text');
                      if (Utils.isEmpty(text)) {
                        return;
                      }
                      searchTrk(text, false);
                    },
                    // autofocus: true,
                    decoration: InputDecoration(
                      suffixIcon: IconButton(
                        padding: EdgeInsets.all(2.0),
                        icon: Icon(
                          Icons.qr_code_scanner,
                          size: 28,
                          color: MyAppTheme.nearlyBlue,
                        ),
                        onPressed: () {
                          // requestPermissions();
                          // Utils.scanBarcode(context);
                          Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                            return ScanCode();
                          })).then((text) {
                            if (text == null) {
                              return;
                            }
                            setState(() {
                              textEditingController.text = text;
                            });
                            print(text); //拿到扫描结果
                            searchTrk(text, false);
                          });
                        },
                      ),
                      border: OutlineInputBorder(
                        borderSide: BorderSide(
                          color: MyAppTheme.nearlyBlue,
                        ),
                        borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                      ),
                      enabledBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                        // 设置焦点之外的边框颜色
                        borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                      ),
                      focusedBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                        // 设置焦点时的边框颜色
                        borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                      ),
                      hintText: "scan tracking number",
                      filled: true,
                      fillColor: MyAppTheme.white,
                      //隐藏下划线
                      //border: InputBorder.none,
                      hintStyle: TextStyle(color: Colors.grey),
                      contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 15),
                    ),
                    onChanged: (text) {
                      code = text;
                    },
                  ),
                ),
              ),
            ],
          ),
          Row(
            children: [
              Expanded(
                flex: 1,
                child: ConstrainedBox(
                  constraints: BoxConstraints(maxHeight: 35),
                  child: TextField(
                    focusNode: skuFocusNode,
                    controller: skuEditingController,
                    textInputAction: TextInputAction.search,
                    onSubmitted: (String text) {
                      print('Searching for $text');
                      if (Utils.isEmpty(text)) {
                        return;
                      }
                    },
                    // autofocus: true,
                    decoration: InputDecoration(
                      suffixIcon: IconButton(
                        padding: EdgeInsets.all(2.0),
                        icon: Icon(
                          Icons.qr_code_scanner,
                          size: 28,
                          color: MyAppTheme.nearlyBlue,
                        ),
                        onPressed: () {
                          // requestPermissions();
                          // Utils.scanBarcode(context);
                          Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                            return ScanCode();
                          })).then((text) {
                            print(text); //拿到扫描结
                          });
                        },
                      ),
                      border: OutlineInputBorder(
                        borderSide: BorderSide(
                          color: MyAppTheme.nearlyBlue,
                        ),
                        borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                      ),
                      enabledBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                        // 设置焦点之外的边框颜色
                        borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                      ),
                      focusedBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                        // 设置焦点时的边框颜色
                        borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                      ),
                      hintText: "scan sku/barcode",
                      filled: true,
                      fillColor: MyAppTheme.white,
                      //隐藏下划线
                      //border: InputBorder.none,
                      hintStyle: TextStyle(color: Colors.grey),
                      contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 15),
                    ),

                    onChanged: (text) {
                      if (text == null) {
                        return;
                      }
                      if (finalProcessTrk == null) {
                        return;
                      }
                      List<String> barcodes = finalProcessTrk.barcodes;
                      for (int i = 0; i < barcodes.length; i++) {
                        if (Utils.isEmpty(barcodes[i])) {
                          continue;
                        }
                        if (barcodes[i].toLowerCase() == text.toLowerCase()) {
                          setState(() {
                            skuEditingController.text = text;
                            qtyFocusNode.requestFocus();
                          });

                          i = barcodes.length;
                        }
                      }
                    },
                  ),
                ),
              ),
            ],
          ),
          Row(
            children: [
              Text(
                "*",
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(color: MyAppTheme.red, fontSize: 14.0),
              ),
              Text(
                "QTY: ",
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
              ),
              Expanded(
                flex: 1,
                child: ConstrainedBox(
                  constraints: BoxConstraints(maxHeight: 35),
                  child: TextField(
                    focusNode: qtyFocusNode,
                    keyboardType: TextInputType.number,
                    controller: qtyEditingController,
                    textInputAction: TextInputAction.search,
                    onSubmitted: (String text) {
                      print('Searching for $text');
                      if (Utils.isEmpty(text)) {
                        return;
                      }
                    },
                  ),
                ),
              ),
              SizedBox(
                width: 5,
              ),
              GestureDetector(
                onTap: () {
                  if (Utils.isEmpty(qtyEditingController.text)) {
                    return;
                  }
                  if (!Utils.isInteger(qtyEditingController.text)) {
                    return;
                  }
                  int qty = int.parse(qtyEditingController.text);
                  if (qty < 1) {
                    qtyEditingController.text = "0";
                    return;
                  }
                  qty--;
                  qtyEditingController.text = "${qty}";
                },
                child: Icon(
                  Icons.remove_circle_outline,
                  size: 35,
                  color: MyAppTheme.nearlyBlue,
                ),
              )
            ],
          ),
          Visibility(
              visible: retape,
              child: Text(
                "Need to be retaped",
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(color: MyAppTheme.red, fontSize: 14.0),
              )),
          SizedBox(
            height: 5,
          ),
          Text(
            "pending Trk# List:",
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
          ),
          SizedBox(
            height: 5,
          ),
          Expanded(
            flex: 1,
            child: setListView(),
          ),
        ],
      ),
    );
  }

  ListView setListView() {
    return ListView.builder(
      itemCount: data == null ? 0 : data.length,
      itemBuilder: (context, index) {
        FinalProcessLpn tally = data[index];
        return Column(
          children: [
            GestureDetector(
              onTap: () {},
              child: Text(
                "${Utils.getStringisEmpty(tally.trackingCode)}(${Utils.getStringisEmpty(tally.type)})",
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(color: MyAppTheme.color_333333, fontSize: 12.0),
              ),
            ),
            Divider(),
          ],
        );
      },
    );
  }

  void returnCheckTrackingCode(String id, bool isNext) async {
    setState(() {
      updateHint('');
      finalProcessTrk = null;
      skuEditingController.text = "";
      qtyEditingController.text = "0";
      retape = false;
    });

    Map<String, dynamic> map = new HashMap();
    map["id"] = id;

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.returnCheckTrackingCode, params: map);

    if (baseResponse.status == 200) {
      finalProcessTrk = FinalProcessTrk.fromJson(baseResponse.data);
      if (finalProcessTrk == null) {
        return;
      }
      setState(() {
        if (finalProcessTrk.barcodes == null) {
          finalProcessTrk.barcodes = new List();
        }
        if (finalProcessTrk.sku == null) {
          finalProcessTrk.barcodes = new List();
        }
        if (finalProcessTrk.retape == 1) {
          retape = true;
        } else {
          retape = false;
        }
        if (Utils.isEmpty(finalProcessTrk.sku)) {
          skuEditingController.text = "";
          skuFocusNode.requestFocus();
        } else {
          finalProcessTrk.barcodes.add(finalProcessTrk.sku);
          skuEditingController.text = finalProcessTrk.sku;
          qtyFocusNode.requestFocus();
        }
      });
      if (isNext) {
        determineType();
      }
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  @override
  void showFileUploadData(String path, int type, int position, bool isSubmit) {
    // TODO: implement showFileUploadData
  }

  @override
  void setNext() {
    if (Utils.isEmpty(textEditingController.text)) {
      ToastContext().init(context);
      Toast.show("Please input  trk#", duration: Toast.lengthShort, gravity: Toast.bottom);
      return;
    }
    if (finalProcessTrk == null) {
      searchTrk(textEditingController.text, true);
      return;
    }
    determineType();
  }

  void searchTrk(String value, bool isNext) {
    bool isExist = false;
    if (data == null) {
      setState(() {
        hint = "Invalid TRK# number";
      });
      return;
    }
    for (int i = 0; i < data.length; i++) {
      FinalProcessLpn finalProcessLpnTemp = data[i];
      if (finalProcessLpnTemp.trackingCode.toLowerCase() == value.toLowerCase()) {
        isExist = true;
        returnCheckTrackingCode("${finalProcessLpnTemp.id}", isNext);
        i = data.length;
        ;
      }
    }
    if (!isExist) {
      setState(() {
        hint = "Invalid TRK# number";
      });
    }
  }

  @override
  void setReset() {
    setState(() {
      textEditingController.text = "";
      hint = "";
      finalProcessTrk = null;
      skuEditingController.text = "";
      qtyEditingController.text = "0";
      retape = false;
      textFiledNode.requestFocus();
    });
  }

  void determineType() {
    ToastContext().init(context);
    if (finalProcessTrk == null) {
      Toast.show("Please input  trk#", duration: Toast.lengthShort, gravity: Toast.bottom);
      return;
    }
    if (finalProcessTrk.type == null) {
      return;
    }
    if (Utils.isEmpty(qtyEditingController.text)) {
      Toast.show("Please input quantity", duration: Toast.lengthShort, gravity: Toast.bottom);
      return;
    }
    if (!Utils.isInteger(qtyEditingController.text)) {
      Toast.show("Please input quantity", duration: Toast.lengthShort, gravity: Toast.bottom);
      return;
    }
    int qty = int.parse(qtyEditingController.text);
    if (qty != Utils.getIntegerisEmpty(finalProcessTrk.quantity)) {
      Toast.show("Please input quantity", duration: Toast.lengthShort, gravity: Toast.bottom);
      return;
    }

    String hint = "";
    //类型  D：指定销毁 D2：系统销毁 P：上架 R：返还客户  RP：重新拍照
    if (finalProcessTrk.type == "D") {
      //指定销毁
      hint = "please put it in a new inboundLPN,then putaway and destroy." + (finalProcessTrk.accountId != null ? (" LPN include ID：${finalProcessTrk.accountId}") : "") + "";
    }
    if (finalProcessTrk.type == "D2") {
      //系统销毁
      hint = "please put it in a new inboundLPN,then putaway and destroy." + (finalProcessTrk.accountId != null ? (" LPN include ID：${finalProcessTrk.accountId}") : "") + "";
    }
    if (finalProcessTrk.type == "P") {
      //上架
      hint = "please put it in a new inboundlpn ，and then putaway.";
    }
    if (finalProcessTrk.type == "R") {
      //返还客户
      hint = "Need to return it to customer，Please put it in inbound lpn. Waiting for customers to pick it" + (finalProcessTrk.accountId != null ? (" , LPN include ID：${finalProcessTrk.accountId}") : "") + ".";
    }
    if (finalProcessTrk.type == "RP") {
      //重新拍照
      hint = "please redo PreProcess for it！Keep it in the original inbound lpn";
    }

    showDialog(
      context: context,
      builder: (context) => FinalProcessTrkTypeDialog(processType: hint, finalProcessTrk: finalProcessTrk),
    ).then((value) => {
          if (value != null && value)
            {
              if (qty > 1)
                {
                  showDialog(
                    context: context,
                    builder: (context) => FinalProcessTrkTypeDialog(processType: hint, finalProcessTrk: finalProcessTrk),
                  ).then((value2) => {
                        if (value2 != null && value2) {setNextData(qty)}
                      })
                }
              else
                {setNextData(qty)}
            }
        });
  }

  void setNextData(int qty) {
    FinalProcessQr finalProcessQr = new FinalProcessQr();
    finalProcessQr.batchNo = batchNo;
    finalProcessQr.oldIbLpn = oldIbLpn;
    finalProcessQr.returnBatchDetailId = "${finalProcessTrk.id}";
    finalProcessQr.trackingCode = finalProcessTrk.trackingCode;
    finalProcessQr.type = finalProcessTrk.type;
    finalProcessQr.sku = finalProcessTrk.sku;
    finalProcessQr.newSku = finalProcessTrk.newSku;
    finalProcessQr.quantity = qty;
    finalProcessQr.account = finalProcessTrk.account;
    finalProcessQr.openLassSku = finalProcessTrk.openLassSku;
    finalProcessQr.accountId = finalProcessTrk.accountId;
    finalProcessQr.retape = finalProcessTrk.retape;

    if (finalProcessTrk.type == "RP") {
      //重新拍照
      Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => FinalProcessRPScreen(finalProcessQr: finalProcessQr)),
      ).then((value) {
        if (value == null) {
        } else if (value is bool) {
          Navigator.pop(context, true);
        } else if (value is FinalProcessReturn) {
          FinalProcessReturn finalProcessReturn = value;
          if (finalProcessReturn.trackingCode == null || finalProcessReturn.trackingCode.length == 0) {
            Navigator.pop(context, finalProcessReturn);
          }
          setState(() {
            textEditingController.text = "";
            hint = "";
            finalProcessTrk = null;
            skuEditingController.text = "";
            qtyEditingController.text = "0";
            retape = false;
            textFiledNode.requestFocus();
            data = finalProcessReturn.trackingCode;
          });
        }
      }).catchError((error) {
        // 错误处理
        print("An error occurred: $error");
      });
      return;
    }

    // Bundle bundle = new Bundle();
    // bundle.putSerializable("FinalProcessQr", finalProcessQr);
    // AppRouter.showActivityForResult(activity, FinalProcessSubmitActivity.class, bundle, Constants.ForResult2);
  }
}
